<?php

namespace App\Admin\Controllers;

use App\Models\Message;
use App\Models\Payment;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Wallet;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\MessageBag;

class TopUpController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header(trans('admin.menu_titles.top_up_apply'))
//            ->description('description')
            ->row(function (Row $row) {
                $row->column(12, $this->grid());
                $row->column(12, $this->history_grid());

            });
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header(trans('admin.menu_titles.top_up_apply'))
//            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header(trans('admin.menu_titles.top_up_apply'))
//            ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header(trans('admin.menu_titles.top_up_apply'))
//            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Payment);
        $grid->setTitle(trans('admin.new_apply'));
        $grid->model()->where('action', Payment::TOP_UP)->where('status', Payment::PENDING)->orderBy('status', 'asc')->orderBy('created_at', 'desc');
        $grid->model()->select('payments.*', 'users.username', 'users.nick_name', 'users.avatar')
            ->join('users', 'user_id', 'users.id');
        $grid->id('Id');
        $grid->username(trans('admin.username'))->modal(trans('admin.detail'), function ($model) {
            $data = $model->user()->first()->wallet()->select('balance')->first();

            $rows = [
                trans('admin.balance') => $data->balance,
            ];

            return new Table([trans('admin.wallet_info'), trans('admin.value')], $rows);

        });
        $grid->nick_name(trans('admin.nick_name'));
        $grid->account(trans('admin.top_up_account'));
        $grid->avatar(trans('admin.avatar'))->lightbox(['width' => 50, 'height' => 50]);
        $grid->payment_method(trans('admin.payment_method'))->display(function ($value) {
            $data = $this->getPayMethod();

            return $data[$value];
        });
        $grid->amount(trans('admin.amount'));
        $grid->status(trans('admin.status'))->display(function ($value) {
            return Payment::$STATUS_MAP[$value];
        });
        $grid->created_at(trans('admin.created_at'));

//        $grid->updated_at('Updated at');
        $grid->disableCreateButton();

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
//            $actions->disableEdit();
            if ($actions->row->status != 'pending') {
                $actions->disableEdit();
            }
            $actions->disableDelete();
        });
        $grid->filter(function ($filter) {
            $filter->column(1 / 3, function ($filter) {
                $filter->between('balance', trans('admin.balance'));
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->like('nick_name', trans('admin.nick_name'));
                $filter->between('amount', trans('admin.amount'));
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->like('username', trans('admin.username'));
            });
        });
        $grid->disablePagination();

        $grid->disableCreateButton();

        $grid->disableFilter();

        $grid->disableRowSelector();

        $grid->disableTools();

        $grid->disableExport();

        return $grid;
    }

    protected function history_grid()
    {
        $grid = new Grid(new Payment);
        $grid->setTitle(trans('admin.history'));
        $grid->model()->where('action', Payment::TOP_UP)->where('status', '!=', Payment::PENDING)->orderBy('status', 'asc')->orderBy('updated_at', 'desc');
        $grid->model()->select('payments.*', 'users.username', 'users.nick_name', 'users.avatar', 'wallets.balance')
            ->join('users', 'user_id', 'users.id')
            ->join('wallets', 'wallets.user_id', 'users.id');
        $grid->id('Id')->totalRow(trans('admin.total'));
        $grid->username(trans('admin.username'));
        $grid->nick_name(trans('admin.nick_name'));
        $grid->avatar(trans('admin.avatar'))->lightbox(['width' => 50, 'height' => 50]);
        $grid->account(trans('admin.top_up_account'));
        $grid->payment_method(trans('admin.payment_method'))->display(function ($value) {
            $data = $this->getPayMethod();

            return $data[$value];
        });
        $grid->amount(trans('admin.amount'))->totalRow(function ($amount) {
            return "<span class='text-danger text-bold'><i class='fa fa-dollar'></i> {$amount} </span>";
        });
        $grid->status(trans('admin.status'))->display(function ($value) {
            return Payment::$STATUS_MAP[$value];
        });
        $grid->created_at(trans('admin.created_at'));

        $grid->updated_at(trans('admin.updated_at'));
        $grid->disableCreateButton();
        $grid->disableActions();
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
//            $actions->disableEdit();
            if ($actions->row->status != 'pending') {
                $actions->disableEdit();
            }
            $actions->disableDelete();
        });
        $grid->filter(function ($filter) {

            $filter->column(1 / 3, function ($filter) {
                $filter->like('nick_name', trans('admin.nick_name'));

            });
            $filter->column(1 / 3, function ($filter) {
                $filter->like('username', trans('admin.username'));
                $filter->between('amount', trans('admin.amount'));
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->like('account', trans('admin.top_up_account'));
                $filter->in('status', trans('admin.status'))->checkbox(array_except(Payment::$STATUS_MAP, Payment::PENDING));
            });
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Payment::findOrFail($id));

        $show->id('Id');
        $show->user_id('User id');
        $show->payment_method('Payment method');
        $show->amount('Amount');
        $show->action('Action');
        $show->status('Status');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Payment);
        $form->setTitle(trans('admin.review'));
        $form->display('account', trans('admin.top_up_account'));
        $form->display('acc_password', trans('admin.top_up_acc_password'));
        $form->display('payment_method', trans('admin.payment_method'))->with(function ($value) {
            return Payment::getPayMethod()[$value];
        });
        $form->decimal('amount', trans('admin.amount'))->rules('required|min:0')->setLabelClass(['required'])->default(0);
        $form->radio('status', trans('admin.status'))->options(Payment::$STATUS_MAP);
        $form->html(trans('admin.sys_messages.top_up_success_info'));
        $form->html(trans('admin.reply'));
        $form->hidden('title', trans('admin.title'))->default(trans('admin.top_up_messages'));
        $form->text('content', trans('admin.content'));
        $form->ignore(['title', 'content']);
        $form->saved(function ($form) {
            //通知用户
            if (Input::get('content')) {
                Message::create([
                    'user_id' => $form->model()->user_id,
                    'title' => Input::get('title'),
                    'content' => Input::get('content'),
                ]);
            }

            //如果成功 充值
            if ($form->model()->status == Payment::SUCCESS) {
                DB::transaction(function () use ($form) {
                    try {

                        $user = User::find($form->model()->user->id);

                        $user->wallet->balance += getMoneyFormat($form->model()->amount);

                        //记录
                        $user->logBalance()->create([
                            'user_balance' => $user->wallet->balance,
                            'action' => Payment::TOP_UP,
                            'amount' => getMoneyFormat($form->model()->amount),
                        ]);

                        $user->push();
                    } catch ( \Exception $exception ) {
                        $error = new MessageBag([
                            'title' => trans('admin.sys_messages.sys_top_up_fail'),
                            'message' => trans('admin.sys_messages.please_top_up_operated'),
                        ]);

                        return back()->with(compact('error'));
                    }
                });

                $success = new MessageBag([
                    'title' => trans('admin.top_up'),
                    'message' => trans('admin.sys_messages.sys_top_up_success'),
                ]);

                return redirect(route('top_up_apply.index'))->with(compact('success'));

            }
        });
        $form->disableEditingCheck();

        $form->disableCreatingCheck();

        $form->disableViewCheck();

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
//            $tools->disableList();
        });

        return $form;
    }
}
